import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Input, 
  Form, 
  Modal, 
  Space, 
  Tag, 
  Tooltip, 
  Popconfirm, 
  Switch, 
  Select,
  Row,
  Col,
  Divider,
  Typography,
  Badge,
  message,
  Tabs,
  ColorPicker,
  Slider,
  Radio
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  InfoCircleOutlined,
  SearchOutlined,
  FilterOutlined,
  ExportOutlined,
  ImportOutlined,
  SettingOutlined,
  EyeOutlined,
  CopyOutlined,
  ArrowRightOutlined,
  ArrowLeftOutlined,
  SwapOutlined,
  BranchesOutlined,
  NodeIndexOutlined
} from '@ant-design/icons';

const { Title, Text } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

/**
 * 图谱关系类型管理组件
 * 用于管理和自定义图谱中的关系类型
 */
const GraphRelationTypeManager = ({ 
  relationTypes = [], 
  onUpdate,
  graphType = 'knowledge',
  readonly = false 
}) => {
  const [form] = Form.useForm();
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [previewModalVisible, setPreviewModalVisible] = useState(false);
  const [currentRelation, setCurrentRelation] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [filterType, setFilterType] = useState('all');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);

  // 预设关系类型模板
  const relationTypeTemplates = {
    knowledge: [
      { name: '包含', identifier: 'contains', description: '表示一个实体包含另一个实体', example: '人工智能 包含 机器学习', isDirected: true, color: '#1677ff' },
      { name: '属于', identifier: 'belongs_to', description: '表示一个实体属于另一个实体', example: '机器学习 属于 人工智能', isDirected: true, color: '#00b96b' },
      { name: '关联', identifier: 'related_to', description: '表示两个实体之间存在关联关系', example: '深度学习 关联 神经网络', isDirected: false, color: '#722ed1' },
      { name: '等价', identifier: 'equivalent_to', description: '表示两个实体在某种意义上等价', example: 'AI 等价 人工智能', isDirected: false, color: '#fa8c16' },
      { name: '部分-整体', identifier: 'part_of', description: '表示部分与整体的关系', example: '神经元 部分-整体 神经网络', isDirected: true, color: '#fa541c' }
    ],
    concept: [
      { name: '是一种', identifier: 'is_a', description: '表示类型关系', example: '狗 是一种 动物', isDirected: true, color: '#1677ff' },
      { name: '有一个', identifier: 'has_a', description: '表示拥有关系', example: '汽车 有一个 引擎', isDirected: true, color: '#00b96b' },
      { name: '导致', identifier: 'causes', description: '表示因果关系', example: '下雨 导致 路面湿滑', isDirected: true, color: '#ff4d4f' },
      { name: '相关', identifier: 'related', description: '表示相关关系', example: '学习 相关 记忆', isDirected: false, color: '#722ed1' },
      { name: '对立', identifier: 'opposite_to', description: '表示对立关系', example: '热 对立 冷', isDirected: false, color: '#fa8c16' }
    ],
    social: [
      { name: '朋友', identifier: 'friend_of', description: '表示朋友关系', example: '张三 朋友 李四', isDirected: false, color: '#00b96b' },
      { name: '关注', identifier: 'follows', description: '表示关注关系', example: '用户A 关注 用户B', isDirected: true, color: '#1677ff' },
      { name: '合作', identifier: 'collaborates_with', description: '表示合作关系', example: '公司A 合作 公司B', isDirected: false, color: '#722ed1' },
      { name: '亲属', identifier: 'relative_of', description: '表示亲属关系', example: '父亲 亲属 儿子', isDirected: false, color: '#fa541c' },
      { name: '通信', identifier: 'communicates_with', description: '表示通信关系', example: '设备A 通信 设备B', isDirected: false, color: '#13c2c2' }
    ]
  };

  // 初始化默认关系类型
  useEffect(() => {
    if (relationTypes.length === 0 && relationTypeTemplates[graphType]) {
      const defaultTypes = relationTypeTemplates[graphType].map((type, index) => ({
        ...type,
        id: `default_${index}`,
        isSystem: true
      }));
      onUpdate?.(defaultTypes);
    }
  }, [graphType, relationTypes.length, onUpdate]);

  // 表格列定义
  const columns = [
    {
      title: '关系名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (text, record) => (
        <Space>
          <div 
            style={{ 
              width: 12, 
              height: 12, 
              borderRadius: '50%', 
              background: record.color || '#1677ff',
              display: 'inline-block'
            }} 
          />
          <span style={{ fontWeight: 500 }}>{text}</span>
          {record.isSystem && <Tag color="blue" size="small">系统</Tag>}
          {record.isDirected && <Tag color="green" size="small">有向</Tag>}
        </Space>
      ),
    },
    {
      title: '标识符',
      dataIndex: 'identifier',
      key: 'identifier',
      width: 120,
      render: (text) => <Text code>{text}</Text>
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          <Text type="secondary">{text}</Text>
        </Tooltip>
      ),
    },
    {
      title: '示例',
      dataIndex: 'example',
      key: 'example',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          <Text italic style={{ color: '#666' }}>{text}</Text>
        </Tooltip>
      ),
    },
    {
      title: '使用次数',
      dataIndex: 'usageCount',
      key: 'usageCount',
      width: 80,
      render: (count = 0) => (
        <Badge count={count} showZero color="#52c41a" />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="预览">
            <Button 
              type="text" 
              size="small"
              icon={<EyeOutlined />} 
              onClick={() => handlePreview(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button 
              type="text" 
              size="small"
              icon={<EditOutlined />} 
              onClick={() => handleEdit(record)}
              disabled={readonly || record.isSystem}
            />
          </Tooltip>
          <Tooltip title="复制">
            <Button 
              type="text" 
              size="small"
              icon={<CopyOutlined />} 
              onClick={() => handleCopy(record)}
              disabled={readonly}
            />
          </Tooltip>
          <Popconfirm
            title="确定删除此关系类型吗？"
            description="删除后将无法恢复，已使用此类型的关系将变为未分类。"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
            disabled={readonly || record.isSystem}
          >
            <Tooltip title="删除">
              <Button 
                type="text" 
                size="small"
                danger 
                icon={<DeleteOutlined />} 
                disabled={readonly || record.isSystem}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理预览
  const handlePreview = (record) => {
    setCurrentRelation(record);
    setPreviewModalVisible(true);
  };

  // 处理编辑
  const handleEdit = (record) => {
    setCurrentRelation(record);
    form.setFieldsValue({
      name: record.name,
      identifier: record.identifier,
      description: record.description,
      example: record.example,
      isDirected: record.isDirected,
      color: record.color || '#1677ff',
      weight: record.weight || 1,
      style: record.style || 'solid'
    });
    setEditModalVisible(true);
  };

  // 处理复制
  const handleCopy = (record) => {
    const copiedRelation = {
      ...record,
      id: `relation_type_${Date.now()}`,
      name: `${record.name}_副本`,
      identifier: `${record.identifier}_copy`,
      isSystem: false
    };
    const updatedTypes = [...relationTypes, copiedRelation];
    onUpdate?.(updatedTypes);
    message.success(`已复制关系类型：${record.name}`);
  };

  // 处理删除
  const handleDelete = (record) => {
    const updatedTypes = relationTypes.filter(item => item.identifier !== record.identifier);
    onUpdate?.(updatedTypes);
    message.success(`已删除关系类型：${record.name}`);
  };

  // 批量删除
  const handleBatchDelete = () => {
    const updatedTypes = relationTypes.filter(item => 
      !selectedRowKeys.includes(item.id) || item.isSystem
    );
    onUpdate?.(updatedTypes);
    setSelectedRowKeys([]);
    message.success(`已删除 ${selectedRowKeys.length} 个关系类型`);
  };

  // 处理添加
  const handleAdd = () => {
    setCurrentRelation(null);
    form.resetFields();
    form.setFieldsValue({
      color: '#1677ff',
      weight: 1,
      style: 'solid',
      isDirected: true
    });
    setEditModalVisible(true);
  };

  // 保存关系类型
  const handleSave = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      
      // 检查标识符是否重复
      const existingIdentifiers = relationTypes
        .filter(item => currentRelation ? item.id !== currentRelation.id : true)
        .map(item => item.identifier);
      
      if (existingIdentifiers.includes(values.identifier)) {
        message.error('标识符已存在，请使用其他标识符');
        return;
      }
      
      let updatedTypes;
      
      if (currentRelation) {
        // 编辑现有类型
        updatedTypes = relationTypes.map(item => 
          item.id === currentRelation.id ? { ...item, ...values } : item
        );
        message.success('关系类型已更新');
      } else {
        // 添加新类型
        const newRelation = {
          ...values,
          id: `relation_type_${Date.now()}`,
          isSystem: false,
          usageCount: 0
        };
        updatedTypes = [...relationTypes, newRelation];
        message.success('关系类型已添加');
      }
      
      onUpdate?.(updatedTypes);
      setEditModalVisible(false);
    } catch (error) {
      console.error('保存失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 导入预设模板
  const handleImportTemplate = (templateType) => {
    const templates = relationTypeTemplates[templateType] || [];
    const newTypes = templates.map((template, index) => ({
      ...template,
      id: `template_${templateType}_${index}_${Date.now()}`,
      isSystem: false,
      usageCount: 0
    }));
    
    const updatedTypes = [...relationTypes, ...newTypes];
    onUpdate?.(updatedTypes);
    message.success(`已导入 ${newTypes.length} 个${templateType}图谱关系类型`);
  };

  // 过滤关系类型
  const filteredRelationTypes = relationTypes.filter(item => {
    const matchesSearch = item.name.toLowerCase().includes(searchText.toLowerCase()) || 
                         item.description.toLowerCase().includes(searchText.toLowerCase()) ||
                         item.identifier.toLowerCase().includes(searchText.toLowerCase());
    
    const matchesFilter = filterType === 'all' || 
                         (filterType === 'system' && item.isSystem) ||
                         (filterType === 'custom' && !item.isSystem) ||
                         (filterType === 'directed' && item.isDirected) ||
                         (filterType === 'undirected' && !item.isDirected);
    
    return matchesSearch && matchesFilter;
  });

  // 转换为表格数据
  const tableData = filteredRelationTypes.map(item => ({
    key: item.id,
    ...item,
  }));

  // 行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    getCheckboxProps: (record) => ({
      disabled: record.isSystem || readonly,
    }),
  };

  return (
    <div style={{ padding: '0' }}>
      <Card 
        title={
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <Space>
              <BranchesOutlined style={{ color: '#1677ff' }} />
              <Title level={4} style={{ margin: 0 }}>关系类型管理</Title>
              <Badge count={relationTypes.length} showZero color="#52c41a" />
            </Space>
          </div>
        }
        extra={
          <Space wrap>
            <Input.Search
              placeholder="搜索关系类型..."
              allowClear
              prefix={<SearchOutlined />}
              onSearch={value => setSearchText(value)}
              onChange={e => setSearchText(e.target.value)}
              style={{ width: 220 }}
            />
            <Select
              value={filterType}
              onChange={setFilterType}
              style={{ width: 120 }}
              placeholder="筛选类型"
            >
              <Option value="all">全部</Option>
              <Option value="system">系统</Option>
              <Option value="custom">自定义</Option>
              <Option value="directed">有向</Option>
              <Option value="undirected">无向</Option>
            </Select>
            {!readonly && (
              <>
                {selectedRowKeys.length > 0 && (
                  <Popconfirm
                    title={`确定删除选中的 ${selectedRowKeys.length} 个关系类型吗？`}
                    onConfirm={handleBatchDelete}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button danger icon={<DeleteOutlined />}>
                      批量删除 ({selectedRowKeys.length})
                    </Button>
                  </Popconfirm>
                )}
                <Button 
                  icon={<ImportOutlined />}
                  onClick={() => {
                    Modal.info({
                      title: '导入预设模板',
                      width: 600,
                      content: (
                        <div style={{ marginTop: 16 }}>
                          <Row gutter={[16, 16]}>
                            {Object.entries(relationTypeTemplates).map(([key, templates]) => (
                              <Col span={8} key={key}>
                                <Card 
                                  size="small" 
                                  hoverable
                                  onClick={() => {
                                    handleImportTemplate(key);
                                    Modal.destroyAll();
                                  }}
                                  style={{ textAlign: 'center' }}
                                >
                                  <NodeIndexOutlined style={{ fontSize: 24, color: '#1677ff', marginBottom: 8 }} />
                                  <div style={{ fontWeight: 500 }}>{key === 'knowledge' ? '知识图谱' : key === 'concept' ? '概念图谱' : '社交网络'}</div>
                                  <div style={{ fontSize: 12, color: '#666' }}>{templates.length} 个关系类型</div>
                                </Card>
                              </Col>
                            ))}
                          </Row>
                        </div>
                      ),
                      okText: '关闭'
                    });
                  }}
                >
                  导入模板
                </Button>
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={handleAdd}
                >
                  添加关系类型
                </Button>
              </>
            )}
          </Space>
        }
        styles={{ body: { padding: '16px 24px' } }}
      >
        <Table 
          columns={columns} 
          dataSource={tableData} 
          rowSelection={readonly ? undefined : rowSelection}
          pagination={{ 
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }}
          size="middle"
          scroll={{ x: 800 }}
          loading={loading}
        />
      </Card>

      {/* 编辑/添加模态框 */}
      <Modal
        title={
          <Space>
            <BranchesOutlined />
            {currentRelation ? "编辑关系类型" : "添加关系类型"}
          </Space>
        }
        open={editModalVisible}
        onOk={handleSave}
        onCancel={() => setEditModalVisible(false)}
        width={700}
        confirmLoading={loading}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          style={{ marginTop: 16 }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="关系名称"
                rules={[{ required: true, message: '请输入关系名称' }]}
              >
                <Input placeholder="例如：包含、属于、关联" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="identifier"
                label="标识符"
                rules={[
                  { required: true, message: '请输入标识符' },
                  { pattern: /^[a-z_][a-z0-9_]*$/, message: '标识符只能包含小写字母、数字和下划线，且以字母或下划线开头' }
                ]}
                tooltip="用于系统内部标识此关系类型的唯一标识符，建议使用小写英文和下划线"
              >
                <Input placeholder="例如：contains、belongs_to、related_to" />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea rows={3} placeholder="请描述此关系类型的含义和用途" />
          </Form.Item>
          
          <Form.Item
            name="example"
            label="示例"
          >
            <Input placeholder="例如：'人工智能 包含 机器学习'" />
          </Form.Item>
          
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="isDirected"
                label="关系方向"
                valuePropName="checked"
              >
                <Switch 
                  checkedChildren="有向" 
                  unCheckedChildren="无向"
                  style={{ width: 60 }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="color"
                label="颜色"
              >
                <ColorPicker showText />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="weight"
                label="权重"
                tooltip="关系的重要程度，影响图谱中关系线的粗细"
              >
                <Slider min={0.5} max={3} step={0.1} marks={{ 0.5: '细', 1: '中', 2: '粗', 3: '很粗' }} />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="style"
            label="线条样式"
          >
            <Radio.Group>
              <Radio value="solid">实线</Radio>
              <Radio value="dashed">虚线</Radio>
              <Radio value="dotted">点线</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>

      {/* 预览模态框 */}
      <Modal
        title={
          <Space>
            <EyeOutlined />
            关系类型预览
          </Space>
        }
        open={previewModalVisible}
        onCancel={() => setPreviewModalVisible(false)}
        width={600}
        footer={[
          <Button key="edit" type="primary" onClick={() => {
            setPreviewModalVisible(false);
            handleEdit(currentRelation);
          }} disabled={readonly || currentRelation?.isSystem}>
            编辑
          </Button>,
          <Button key="copy" onClick={() => {
            setPreviewModalVisible(false);
            handleCopy(currentRelation);
          }} disabled={readonly}>
            复制
          </Button>,
          <Button key="close" onClick={() => setPreviewModalVisible(false)}>
            关闭
          </Button>
        ]}
      >
        {currentRelation && (
          <div style={{ padding: '16px 0' }}>
            <Row gutter={[16, 16]}>
              <Col span={24}>
                <Card size="small" style={{ marginBottom: 16 }}>
                  <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
                    <div 
                      style={{ 
                        width: 16, 
                        height: 16, 
                        borderRadius: '50%', 
                        background: currentRelation.color || '#1677ff',
                        marginRight: 12
                      }} 
                    />
                    <Title level={4} style={{ margin: 0 }}>{currentRelation.name}</Title>
                    <div style={{ marginLeft: 'auto' }}>
                      {currentRelation.isSystem && <Tag color="blue">系统</Tag>}
                      {currentRelation.isDirected && <Tag color="green">有向</Tag>}
                    </div>
                  </div>
                  <Text code>{currentRelation.identifier}</Text>
                </Card>
              </Col>
              
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>描述：</Text>
                  <div style={{ marginTop: 4 }}>
                    <Text type="secondary">{currentRelation.description || '暂无描述'}</Text>
                  </div>
                </div>
              </Col>
              
              <Col span={12}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>示例：</Text>
                  <div style={{ marginTop: 4 }}>
                    <Text italic style={{ color: '#666' }}>{currentRelation.example || '暂无示例'}</Text>
                  </div>
                </div>
              </Col>
              
              <Col span={24}>
                <Divider />
                <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', padding: '20px 0' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
                    <div style={{ 
                      width: 60, 
                      height: 60, 
                      borderRadius: '50%', 
                      background: '#e6f7ff', 
                      display: 'flex', 
                      alignItems: 'center', 
                      justifyContent: 'center',
                      border: '2px solid #1677ff'
                    }}>
                      <Text strong>A</Text>
                    </div>
                    
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      {currentRelation.isDirected ? (
                        <ArrowRightOutlined style={{ 
                          fontSize: 20, 
                          color: currentRelation.color || '#1677ff',
                          fontWeight: currentRelation.weight || 1
                        }} />
                      ) : (
                        <SwapOutlined style={{ 
                          fontSize: 20, 
                          color: currentRelation.color || '#1677ff',
                          fontWeight: currentRelation.weight || 1
                        }} />
                      )}
                      <Text style={{ 
                        color: currentRelation.color || '#1677ff',
                        fontWeight: 500
                      }}>
                        {currentRelation.name}
                      </Text>
                    </div>
                    
                    <div style={{ 
                      width: 60, 
                      height: 60, 
                      borderRadius: '50%', 
                      background: '#f6ffed', 
                      display: 'flex', 
                      alignItems: 'center', 
                      justifyContent: 'center',
                      border: '2px solid #52c41a'
                    }}>
                      <Text strong>B</Text>
                    </div>
                  </div>
                </div>
              </Col>
              
              <Col span={24}>
                <div style={{ background: '#fafafa', padding: 12, borderRadius: 6 }}>
                  <Row gutter={16}>
                    <Col span={6}>
                      <Text type="secondary">颜色：</Text>
                      <div style={{ 
                        width: 20, 
                        height: 20, 
                        borderRadius: 4, 
                        background: currentRelation.color || '#1677ff',
                        display: 'inline-block',
                        marginLeft: 8,
                        border: '1px solid #d9d9d9'
                      }} />
                    </Col>
                    <Col span={6}>
                      <Text type="secondary">权重：</Text>
                      <Text style={{ marginLeft: 8 }}>{currentRelation.weight || 1}</Text>
                    </Col>
                    <Col span={6}>
                      <Text type="secondary">样式：</Text>
                      <Text style={{ marginLeft: 8 }}>{currentRelation.style === 'dashed' ? '虚线' : currentRelation.style === 'dotted' ? '点线' : '实线'}</Text>
                    </Col>
                    <Col span={6}>
                      <Text type="secondary">使用次数：</Text>
                      <Text style={{ marginLeft: 8 }}>{currentRelation.usageCount || 0}</Text>
                    </Col>
                  </Row>
                </div>
              </Col>
            </Row>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default GraphRelationTypeManager;